﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using OnlineEducation.Models;
using OnlineEducation.Data.Entities;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Console;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using OnlineEducation.Helpers;

namespace OnlineEducation.Data
{
    public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, int,
        IdentityUserClaim<int>, ApplicationUserRole, IdentityUserLogin<int>,
        IdentityRoleClaim<int>, IdentityUserToken<int>>
    {



        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
        {

        }

        public DbSet<ApplicationUser> ApplicationUsers { get; set; }

        public DbSet<ApplicationRole> ApplicationRoles { get; set; }

        public DbSet<ApplicationUserRole> ApplicationUserRole { get; set; }

        public DbSet<Code> Codes { get; set; }

        public DbSet<Course> Courses { get; set; }

        public DbSet<CourseExam> CourseTests { get; set; }

        public DbSet<TeachingEvaluation> CourseEvaluations { get; set; }

        public DbSet<Booking> Bookings { get; set; }

        public DbSet<Lesson> Lessons { get; set; }

        public DbSet<LessonRecord> LessonRecords { get; set; }

        public DbSet<TeachingPlan> TeachingPlans { get; set; }

        public DbSet<TeachingPlanItem> TeachingPlanItems { get; set; }

        public DbSet<Holiday> Holidays { get; set; }


        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);

            builder.Entity<Code>(entity => entity.ToTable("T_Code"));
            builder.Entity<Booking>(entity =>
            {
                entity.ToTable("T_Booking");
                entity.Property(p => p.TotalAmount).HasColumnType("decimal(18,2)");
                entity.Property(p => p.Discount).HasColumnType("decimal(18,2)");

            });

            builder.Entity<Course>(entity =>
            {
                entity.ToTable("T_Course");
                entity.Property(p => p.Price).HasColumnType("decimal(18,2)");
            });

            builder.Entity<Lesson>(entity => entity.ToTable("T_Lesson"));
            builder.Entity<TeachingPlan>(entity => entity.ToTable("T_TeachingPlan"));
            builder.Entity<TeachingPlanItem>(entity => entity.ToTable("T_TeachingPlanItem"));
            builder.Entity<LessonRecord>(entity =>
            {
                entity.ToTable("T_LessonRecord");
                entity.Property(p => p.Point).HasColumnType("decimal(18,2)");
            });
            builder.Entity<TeachingEvaluation>(entity =>
            {
                entity.ToTable("T_TeachingEvaluation");
                entity.Property(p => p.Point).HasColumnType("decimal(18,2)");
            });
            builder.Entity<CourseExam>(entity => entity.ToTable("T_CourseExam"));
            builder.Entity<Holiday>(entity => entity.ToTable("T_Holiday"));

            //builder.Entity<ApplicationUser>()
            //   .HasMany(e => e.UserRoles)
            //   .WithOne()
            //   .HasForeignKey(e => e.UserId)
            //   .IsRequired()
            //   .OnDelete(DeleteBehavior.Restrict);

            //builder.Entity<ApplicationRole>()
            //  .HasMany(e => e.UserRoles)
            //  .WithOne()
            //  .HasForeignKey(e => e.RoleId)
            //  .IsRequired()
            //  .OnDelete(DeleteBehavior.Restrict);

            builder.Entity<ApplicationUserRole>()
                .HasOne(e => e.Role)
                .WithMany("UserRoles")
                .HasForeignKey(e => e.RoleId)
                .IsRequired()
                .OnDelete(DeleteBehavior.Cascade);

            builder.Entity<ApplicationUserRole>()
              .HasOne(e => e.User)
              .WithMany("UserRoles")
              .HasForeignKey(e => e.UserId)
              .IsRequired()
              .OnDelete(DeleteBehavior.Cascade);

        }


        /// <summary>
        /// Adds the specified entity ,only belongs to ApplicationDbContext instead of DbContext(自定义的).
        /// </summary>
        /// <param name="entityBase">The entity base.</param>
        /// <returns></returns>
        public EntityEntry Add(EntityBase entityBase)
        {

            if (HttpContextHelper.Current == null || HttpContextHelper.Current.User == null || HttpContextHelper.Current.User.Identity == null)
            {
                entityBase.UpdatedBy = "System";
                entityBase.CreatedBy = "System";
            }
            else
            {
                entityBase.UpdatedBy = HttpContextHelper.Current.User.Identity.Name ?? "System";
                entityBase.CreatedBy = HttpContextHelper.Current.User.Identity.Name ?? "System";
            }

            entityBase.UpdatedTime = DateTime.Now;
            entityBase.CreatedTime = DateTime.Now;

            return base.Add(entityBase);
        }
        /// <summary>
        /// Updates the specified entity, only belongs to ApplicationDbContext instead of DbContext(自定义的).
        /// </summary>
        /// <param name="entityBase">The entity base.</param>
        /// <returns></returns>
        public EntityEntry Update(EntityBase entityBase)
        {
            if (HttpContextHelper.Current == null || HttpContextHelper.Current.User == null || HttpContextHelper.Current.User.Identity == null)
            {
                entityBase.UpdatedBy = "System";
                entityBase.CreatedBy = "System";
            }
            else
            {
                entityBase.UpdatedBy = HttpContextHelper.Current?.User.Identity.Name ?? "System";
            }

            entityBase.UpdatedTime = DateTime.Now;

            return base.Update(entityBase);

        }
    }
}
